package com.example.yuejian21.nongfusanquan.yuejian21.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.yuejian21.nongfusanquan.yuejian21.R;
import com.example.yuejian21.nongfusanquan.yuejian21.activity.SearchcourseActivity;
import com.example.yuejian21.nongfusanquan.yuejian21.adapter.CourseAdapter;
import com.example.yuejian21.nongfusanquan.yuejian21.javabean.Coursebean;
import com.example.yuejian21.nongfusanquan.yuejian21.model.Coursemodel;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Nongfusanquan on 2017-10-12.
 */

public class CourseFragment extends Fragment {
    private RecyclerView recyclerView;
    private View view = null;
    private ViewPager mViewPaper;
    private List<ImageView> images;
    private List<View> dots;
    private int currentItem;
    private Button searchcourse;

    //记录上一次点的位置
    private int oldPosition = 0;
    //存放图片的id

    private int[] imageIds = new int[]{
            R.drawable.image1,
            R.drawable.image2,
            R.drawable.image3,
            R.drawable.image4,

    };
    //存放图片的标题
    private String[] titles = new String[]{
            "just do it",
            "激情洋溢",
            "basketdancer",
            "网球小王子",
//            "热血屌丝的反杀"
    };
    private TextView title;
    private CourseFragment.ViewPagerAdapter adapter;
    private ScheduledExecutorService scheduledExecutorService;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_course, container, false);
        recyclerView = (RecyclerView) view.findViewById(R.id.rv);
        recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));

        mViewPaper = (ViewPager) view.findViewById(R.id.vp_vip);
        setHasOptionsMenu(true);
        //显示的图片
        images = new ArrayList<ImageView>();
        for (int i = 0; i < imageIds.length; i++) {
            ImageView imageView = new ImageView(getActivity());
            imageView.setBackgroundResource(imageIds[i]);
            images.add(imageView);
        }
        //显示的小点
        dots = new ArrayList<View>();
        dots.add(view.findViewById(R.id.dot_0));
        dots.add(view.findViewById(R.id.dot_1));
        dots.add(view.findViewById(R.id.dot_2));
        dots.add(view.findViewById(R.id.dot_3));


        title = (TextView) view.findViewById(R.id.title);
        title.setText(titles[0]);

        adapter = new CourseFragment.ViewPagerAdapter();
        mViewPaper.setAdapter(adapter);

        mViewPaper.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {


            @Override
            public void onPageSelected(int position) {
                title.setText(titles[position]);
                dots.get(position).setBackgroundResource(R.drawable.image1);
                dots.get(oldPosition).setBackgroundResource(R.drawable.image4);

                oldPosition = position;
                currentItem = position;
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
        initViews();
        initEvent();
        getData();
        return view;
    }
    private void initViews(){


        searchcourse=(Button)view.findViewById(R.id.button_search_course);
    }

    private void initEvent(){
        searchcourse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), SearchcourseActivity.class));

            }
        });
    }

    /**
     * 自定义Adapter
     *
     */
    private class ViewPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return images.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(ViewGroup view, int position, Object object) {
            // TODO Auto-generated method stub

            view.removeView(images.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup view, int position) {
            // TODO Auto-generated method stub
            view.addView(images.get(position));
            return images.get(position);
        }

    }


    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleWithFixedDelay(
                new CourseFragment.ViewPageTask(),
                2,
                2,
                TimeUnit.SECONDS);
    }


    /**
     * 图片轮播任务
     *
     */
    private class ViewPageTask implements Runnable {

        @Override
        public void run() {
            currentItem = (currentItem + 1) % imageIds.length;
            mHandler.sendEmptyMessage(0);
        }
    }

    /**
     * 接收子线程传递过来的数据
     */
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            mViewPaper.setCurrentItem(currentItem);
        }

        ;
    };

    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        if (scheduledExecutorService != null) {
            scheduledExecutorService.shutdown();
            scheduledExecutorService = null;
        }
    }

    //获取列表数据
    private void getData() {
        Coursemodel trainModel=new Coursemodel();
        Call<List<Coursebean>> call=trainModel.getTrainlist();
        // System.out.print("t_name");
        call.enqueue(new Callback<List<Coursebean>>() {
            @Override
            public void onResponse(Call<List<Coursebean>> call, Response<List<Coursebean>> response) {
                List<Coursebean> data = response.body();  //获取数据
                System.out.printf("data");
                recyclerView.setAdapter(new CourseAdapter(CourseFragment.this.getActivity(), data));
            }
            @Override
            public void onFailure(Call<List<Coursebean>> call, Throwable t) {

            }
        });



    }
}